package cn.tedu.v1.v1_2;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * 聊天室  Version 1.1
 * 服务器  功能：1：服务器申请端口号：软件具备端口号
 *             2.在start方法中，等待客户端链接，返回socket
 *               IO读入
 *        【新增】3.所有服务端异常，全部捕获，明确提示
 *              4.关闭serverSocket
 */
public class Server {
    private ServerSocket serverSocket;
    public Server(){
        try {
            serverSocket=new ServerSocket(6666);
            //BindException  端口号已经被占用
        } catch (BindException e){
            System.out.println("请检查端口号，被占用");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    //3.创建start 方法 accept() d等待客户端链接 传输数据：IO
    public void start()  {
        Socket socket=null;
        InputStream is=null;
        InputStreamReader isr=null;
        BufferedReader br=null;
        try {

            System.out.println("等待客户端链接");
            socket=serverSocket.accept();
            //getInetAddress()  返回Address对象，表示远方IP地址
            //具体IP地址  getHostAddress,将远方IP地址转换为字符串，未连接返回null
            String ip=socket.getInetAddress().getHostAddress();
            System.out.println("客户端:"+ip+"连接上了");

            is=socket.getInputStream();

            isr=new InputStreamReader(is,"UTF8");

            br=new BufferedReader(isr);

            while (true){
                String str=br.readLine();
                System.out.println("客户端："+str);
            }
        } catch (UnsupportedEncodingException e){
            System.out.println("请检查客户端与服务器端编码集不一致");
        } catch (SocketException e){
            System.out.println("客户端链接被重置");
        }
        catch (IOException e) {
            System.out.println("客户端链接失效了");
        } finally {
            if (br!=null) {
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("读入流断开链接");
                }
            }
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端socket断开连接");
            }
        }
    }
    public static void main(String[] args){
        Server server=new Server();
        server.start();
    }
}